package a.happy.town.onebook;

import java.util.ArrayList;
import java.util.Scanner;

import static a.happy.town.onebook.UserRegister.*;

/**
 * @BelongsProject: onebook
 * @BelongsPackage: a.happy.town.onebook
 * @Author: ByHappy  (Email:15188881427@163.c0m)
 * @CreateTime: 2023-07-31 00:44
 * @Description:
 * @Version: 1.0
 **/
public class UserForget {

    public static void forgetPassword(ArrayList<UserDTO> list) {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = sc.next();
        boolean flag = contains(list, username);
        if (!flag) {
            System.out.println("当前用户:" + username + "未注册!!!请先注册:");
            return;
        }

        // 键盘录入身份证号码和手机号码
        String personID;
        while (true) {
            System.out.println("请确认您的身份证号码:");
            personID = sc.next();
            boolean flag2 = checkPersonID(personID);
            if (flag2) {
                System.out.println("身份证号码格式 OK! 请进行下一步操作");
                break;
            } else {
                System.out.println("您输入的身份证号码格式错误，请重新输入...");
                continue;
            }
        }
        String phoneNumber;
        while (true) {
            System.out.println("请确认您的手机号码:");
            phoneNumber = sc.next();
            boolean flag3 = checkPhoneNumber(phoneNumber);
            if (flag3) {
                break;
            } else {
                System.out.println("手机号码格式错误，请重新输入...");
                continue;
            }
        }

        // 需要把用户对象通过索引先获取出来
        int index = findIndex(list, username);
        UserDTO userDTO = list.get(index);
        // 比较用户对象中的手机号码和身份证号码是否相同
        if (!(userDTO.getPersonID().equalsIgnoreCase(personID) && userDTO.getPhoneNumber().equals(phoneNumber))) {
            System.out.println("您输入的身份证号码或手机号码输入有误，不能修改密码");
            return;
        }

        //当代码执行到这里，表示所有的数据全部验证成功，直接修改即可
        String password;
        while (true) {
            System.out.println("请输入您的新密码：");
            password = sc.next();
            System.out.println("请再次确认新密码");
            String againPassword = sc.next();
            if (password.equals(againPassword)) {
                System.out.println("两次密码输入一致，OK");
                break;
            } else {
                System.out.println("两次密码输入不一致，请重新输入...");
                continue;
            }
        }

        userDTO.setPassword(password);
        System.out.println("密码修改成功");


    }

    private static int findIndex(ArrayList<UserDTO> list, String username) {
        for (int i = 0; i < list.size(); i++) {
            UserDTO userDTO = list.get(i);
            if (userDTO.getUsername().equals(username)) {
                return i;
            }
        }

        return -1;
    }
}
